<template>
  <div>
    <common-head :title="$route.name"/>
    <div class="container-cart">
      <!-- 购物车数据 -->
      <div v-if="isShow">
        <van-swipe-cell v-for="item in items" :key="item.id">
          <div class="item">
            <van-checkbox v-model="item.selected" class="checkbox" @change="changeItemStates(item.key,item.selected)"/>
            <van-card
              :num="item.number"
              :price="item.price"
              :title="item.name"
              :thumb="item.pic"
            >
              <template #footer>
                <van-stepper v-model="item.number" theme="round" size="22" @change="ChangeItemNums(item.key, item.number)"/>
              </template>
            </van-card>
          </div>
            <template #right>
              <van-button square text="删除" type="danger" class="delete-button" @click="beforeClose(item.key)"/>
            </template>
        </van-swipe-cell>
      </div>
      <!-- 购物车数据 -->
      <!-- 空状态 -->
      <div v-else class="empty-box">
        <van-empty
          class="custom-image"
          image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
          description="您的购物车空空如也哟"
        />
      </div>
    </div>
    <!-- 提交订单 -->
    <van-submit-bar :price="totalPrice*100" button-text="提交订单" v-show="isShow" @submit="toOrder">
      <van-checkbox v-model="allChecked">全选</van-checkbox>
    </van-submit-bar>
    <!-- 提交订单 -->
    <tabbar/>
  </div>
</template>

<script>
import CommonHead from '_components/CommonHead'
import Tabbar from '_components/Tabbar'
import { fetchCart, changeItemNum, changeItemState, delItemCart } from '_api'
import { getToken } from '../../utils/index'

export default {
  name: 'Cart',
  data () {
    return {
      checked: false, // 每个商品的状态
      items: [], // 购物车数据
      totalPrice: 0, // 总价格
      number: 0, // 商品总数量
      isShow: false
    }
  },
  created () {
    this.fetchCarts()
  },
  methods: {
    // 修改商品选中状态
    changeItemStates (key, selected) {
      changeItemState({
        key: key,
        selected: selected,
        token: getToken()
      }).then(res => {
        if (res.data.code === 0) {
          this.items = res.data.data.items
          this.totalPrice = res.data.data.price
          this.number = res.data.data.number
        }
      })
    },
    // 点击增加商品数量
    ChangeItemNums (key, number) {
      changeItemNum({
        key: key,
        number: number,
        token: getToken()
      }).then(res => {
        this.items = res.data.data.items
        this.totalPrice = res.data.data.price
        this.number = res.data.data.number
      })
    },
    // 删除确认提示
    beforeClose (key) {
      this.$dialog.confirm({
        message: '确定删除吗？',
        theme: 'round-button'
      }).then(() => {
        delItemCart({
          key: key,
          token: getToken()
        }).then(res => {
          if (res.data.code === 0) {
            this.$toast.success({
              message: '删除成功',
              duration: 1000,
              onClose: () => {
                this.items = res.data.data.items
                this.totalPrice = res.data.data.price
                this.number = res.data.data.number
              }
            })
          } else if (res.data.code === 700) {
            this.items = []
            this.isShow = false
            this.number = 0
          }
        })
      }).catch(() => {
        // on cancel
      })
    },
    // 提交订单
    toOrder () {
      this.$router.push('/order')
    },
    // 请求购物车数据
    fetchCarts () {
      fetchCart({ token: getToken() }).then(res => {
        if (res.data.code === 0) {
          this.items = res.data.data.items
          this.totalPrice = res.data.data.price
          this.number = res.data.data.number
          this.isShow = true
        }
        if (res.data.code === 700) {
          this.items = []
          this.number = res.data.data.number
          this.isShow = false
        }
      })
    }
  },
  watch: {
    // 通过watch监听每次购物车商品数量的变化，只要变化就触发mutation
    items (newVal) {
      this.$store.commit('cart/change_cart_num', {
        items: this.items,
        number: this.number
      })
    }
  },
  computed: {
    // 每一个商品的变化都会触发全选的变化，因为全选状态依赖于每一个商品状态
    allChecked: {
      get () {
        return this.items.every(item => item.selected)
      },
      set (selected) {
        const keys = []
        this.items.forEach(item => {
          keys.push(item.key)
        })
        changeItemState({
          selected,
          key: keys.join(','),
          token: getToken()
        }).then(res => {
          if (res.data.code === 0) {
            this.items = res.data.data.items
            this.totalPrice = res.data.data.price
            this.number = res.data.data.number
          }
        })
      }
    }
  },
  components: { Tabbar, CommonHead }
}
</script>

<style lang="scss" scoped>
.container-cart{
  padding-bottom:100px;
  .item{
    display: flex;
    background-color: #fff;
    .checkbox{
      margin: 0 5px;
    }
    .van-card{
      flex: 1;
    }
  }
  ::v-deep .van-swipe-cell__right{
    background-color: #fff;
  }
  .goods-card {
      margin: 0;
    }
  .delete-button{
    margin-top: 8px;
    height: 100%;
  }
}
.van-submit-bar{
  bottom: 50px
}
.empty-box{
  .van-empty{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  .custom-image .van-empty__image {
    width: 2.4324rem;
    height: 2.4324rem;
  }
  ::v-deep .van-empty__description{
    padding: 0;
  }
}
</style>
